<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="container">
        <h4 class="jumbotron-heading text-xs-center">Chat Room</h4>
        <p>
            While we are preparing for your payment, we want you to chat with a chatbot for <b>5 minutes</b>.<br>
            After chatting, you will be asked to indicate your feelings and evaluations of the bot.<br>
        </p>
        <p class="lead text-xs-center">
            This page allows you to chat with the bot.
        </p>
        <input type="text" id="player" name="player" placeholder="player">
        <input type="text" id="session" name="session" placeholder="session">
        <input type="text" id="ip" name="ip" placeholder="ip">
        <hr class="my-2">
        <div class="row">
            <div class="col-xs-6 offset-xs-3">
                <ul class="list-group chat-log js-chat-log">
                </ul>
                <div class="input-group input-group-lg mt-1">
                    <input id='textbox' type="text" class="form-control js-text"
                        placeholder="Type something to begin..." required />
                    <span class="input-group-btn">
                        <button id='say' class="btn btn-primary js-say" type="button">Say</button>
                    </span>
                </div>
            </div>
        </div>
    </div>
    <script src="./lib/jquery.min.js"></script>
    <!-- <script src="{% static 'js/js.cookie.js' %}"></script> -->
    <script src="./lib/bootstrap.js"></script>
    <script src="./lib/jquery.xdo.min.js"></script>

    <script>

        //   var csrftoken = Cookies.get('csrftoken');

        function csrfSafeMethod(method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    //   xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        var $chatlog = $('.js-chat-log');
        var $input = $('.js-text');
        var $sayButton = $('.js-say');

        function createRow(text) {
            var $row = $('<li class="list-group-item"></li>');
            $row.text(text);
            $chatlog.append($row);
        }


        function send(id, data, callback,) {
            // var ip = document.getElementById("ip").value;
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/myAddress', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify(
                {
                    "reqType": 0,
                    "perception": {
                        "inputText": {
                            "text": data
                        }
                    },
                    "userInfo": {
                        "apiKey": "a677fd9cff8a4228b702e9bd717c5e7f",
                        "userId": "1"
                    }
                }

            ));
            xhr.onreadystatechange = function () {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    callback(JSON.parse(xhr.responseText).results)
                }

            }

        }
        function addMsg(data, callback) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/addMsg', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify(
                data
            ));
            xhr.onreadystatechange = function () {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    callback(JSON.parse(xhr.responseText).results)
                }

            }
        }
        function say() {
            var text = $input.val();
            var player = document.getElementById("player").value;
            var ip = document.getElementById("ip").value;
            var session = document.getElementById("session").value;
            createRow(text);
            send("Player_", text, function (res) {
                console.log(res, "---res")
                var num = Math.floor(Math.random() * 10 + 1)
                if (num > 5) {
                    let reply = "抱歉,我听不懂你的问题！"
                    createRow(reply);
                    addMsg({ sendMsg: text, receive: reply,player,ip,session }, function () {
                        console.log("add success")
                    })
                } else {
                    if (res === null || text === "") {
                        let reply = 'Enter valid text!'
                        createRow(reply);
                        addMsg({ sendMsg: text, receive: reply,player,ip,session }, function () {
                            console.log("add success")
                        })
                    } else {
                        createRow(res[0].values.text);
                        addMsg({ sendMsg: text, receive: res[0].values.text ,player,ip,session}, function () {
                            console.log("add success")
                        })
                    }
                }


            }
            );


        }

        $sayButton.click(function () {
            say();

        });

        $(document).keypress(function (e) {
            if (e.which === 13) {
                e.preventDefault();
                say();

            }
        });

    </script>

</body>

</html>